package com.ym.ms.filter;

import com.cdk8s.tkey.client.rest.TkeyProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ym.ms.commons.AuthVariable;
import com.ym.ms.utils.CookieUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zetor
 */
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Value("${front_url}")
    private String front_url;

    @Autowired
    private TkeyProperties tkeyProperties;

    //=====================================业务处理 start=====================================
    private boolean resp(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
        if (tkeyProperties.getEnableCodeCallbackToFront()) {
            responseJson(response);
        } else {
            response.sendRedirect(getRedirectUrl(request));
        }
        return false;
    }

    @SneakyThrows
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, Object handler) {

        String accessToken = CookieUtil.getValue(request, AuthVariable.SSO_SESSIONID);
        if (StringUtils.isBlank(accessToken)) {
            log.error("【SSO】Local token is null, to login...");
            return resp(request, response);
        }
        // 本机不校验
        String local_url = InetAddress.getLocalHost().getHostAddress();
        if (request.getRemoteAddr().contains(local_url)) {
            log.info("【SSO】Local to pass...");
            return true;
        }
        if (StringUtils.isNotBlank(front_url)) {
            String token = request.getHeader(AuthVariable.HEADER_TOKEN_KEY);
            if (StringUtils.isBlank(token) || !token.equals(accessToken)) {
                response.sendRedirect(front_url + accessToken);
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }


    private String getRedirectUrl(final HttpServletRequest request) {
        return tkeyProperties.getFinalRedirectUri(request);
    }

    @SneakyThrows
    private void responseJson(final HttpServletResponse response) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Map<String, Object> responseMap = new HashMap<>(4);
        responseMap.put("isSuccess", false);
        responseMap.put("msg", "您还未登录，请先登录");
        responseMap.put("timestamp", Instant.now().toEpochMilli());
        responseMap.put("code", "0");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseMap);
        PrintWriter out = response.getWriter();
        out.print(json);
    }

}
